package com.example.home.government.acivity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.example.home.R;
import com.example.home.government.bean.ImgBean;
import com.example.home.tool.GeneralClass;
import com.example.home.tool.OKHttpTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class AppealOtherMainActivity extends AppCompatActivity {

    private static final int PICK_IMAGE_REQUESTB = 333;
    private ImageView back;
    private EditText title;
    private Button uploadButton;
    private EditText undertaker;
    private EditText iphone;
    private Button btn_send;
    private ImageView imageView;
    private EditText content;
    private String filePath;
    private GeneralClass generalClass;
    private String serviceImgUrl;
    private String listId;
    private static final int REQUEST_PERMISSION_CODE = 1;
    private final static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appeal_other_main);
        Intent integer = getIntent();
        listId = integer.getStringExtra("listIdae");
        verifyStoragePermissions(this);



        initView();
    }

    private void verifyStoragePermissions(AppealOtherMainActivity appealOtherMainActivity) {
        try {
            //判断当前系统是否是Android6.0(对应API 23)以及以上，如果是则判断是否含有了权限
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(this,
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                /***
                 * checkSelfPermission返回两个值
                 * 有权限: PackageManager.PERMISSION_GRANTED
                 * 无权限: PackageManager.PERMISSION_DENIED
                 */
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //回调函数，申请权限后回调onRequestPermissionResult函数，第一个参数为请求码，第二个参数是刚刚请求的权限集，第三个参数是请求结果，0表示授权成功，-1表示授权失败
    //requestCode：这个对应请求状态码，permissions：这个是前面你要申请的权限集合，grantResults：这个是申请权限的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                //grantResults[i]：返回0，表示授权成功，返回-1，表示授权失败
                Log.i("111333", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }
    }

    private void initView() {
        back = findViewById(R.id.back);
        title = findViewById(R.id.title);
        content = findViewById(R.id.content);
        uploadButton = findViewById(R.id.uploadButton);
        undertaker = findViewById(R.id.undertaker);
        iphone = findViewById(R.id.iphone);
        imageView = findViewById(R.id.imageView);
        btn_send = findViewById(R.id.btn_send);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppealOtherMainActivity.this.finish();
            }
        });


        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery(v);
            }
        });

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title1 = title.getText().toString();
                String content1 = content.getText().toString();
                String undertaker1 = undertaker.getText().toString();
                String iphone1 = iphone.getText().toString();
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("title", title1);
                    jsonObject.put("content", content1);
                    jsonObject.put("undertaker", undertaker1);
                    jsonObject.put("iphone", iphone1);
                    jsonObject.put("imgUrl", serviceImgUrl);
                    jsonObject.put("appealCategoryId",listId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (!title1.isEmpty()) {
                    OKHttpTool.doNetRequest("prod-api/api/gov-service-hotline/appeal",
                            OKHttpTool.POST,
                            GeneralClass.class,
                            new OKHttpTool.NetCallback() {
                                @Override
                                public void onSuccess(Object obj) {
                                    runOnUiThread(new Runnable() {
                                        GeneralClass generalClass = (GeneralClass) obj;
                                        @Override
                                        public void run() {
                                            if (generalClass.getCode() == 200) {
                                                Toast.makeText(AppealOtherMainActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                                                AppealOtherMainActivity.this.finish();
                                            } else if (generalClass.getCode() == 500) {
                                                Toast.makeText(AppealOtherMainActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(String msg) {
                                    Log.e("xhf", "网络访问失败");
                                }
                            }, jsonObject.toString());
                } else {
                    Toast.makeText(AppealOtherMainActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }




    public void openGallery(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUESTB);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUESTB && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            String imagePath = getRealPathFromUri(selectedImageUri);

            if (imagePath != null) {
                ImageView imageView = findViewById(R.id.imageView);
                imageView.setImageURI(selectedImageUri);
                uploadButton.setVisibility(View.GONE);
                // 调用上传图片方法
                uploadImage(selectedImageUri);
            } else {
                // 处理无法获取文件路径的情况
                Toast.makeText(AppealOtherMainActivity.this, "上传图片失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    public String getRealPathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(column_index);
                cursor.close();
                return filePath;
            } else {
                cursor.close();
            }
        }
        return null;
    }



    public void uploadImage(Uri imageUri) {
        String filePath = getRealPathFromUri(imageUri);
        File fileToUpload = new File(filePath);
        OKHttpTool.uploadFile(fileToUpload, ImgBean.class, new OKHttpTool.NetCallback() {
            @Override
            public void onSuccess(Object obj) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 上传成功后的处理逻辑
                        // obj 是服务器响应的解析结果，根据您的需求进行处理
                        serviceImgUrl = ((ImgBean) obj).getUrl();
                        Toast.makeText(AppealOtherMainActivity.this,"上传成功",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onFailure(String msg) {
                // 上传失败后的处理逻辑
                // msg 包含了失败的原因，根据您的需求进行处理
                Log.e("xhf","=="+msg);
            }
        });
    }

}